package com.holly.unit.deform.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.holly.unit.core.constants.CommonConstant;
import com.holly.unit.core.enums.QueryRuleEnum;
import com.holly.unit.core.util.RestUtil;
import com.holly.unit.db.api.factory.PageFactory;
import com.holly.unit.db.api.factory.PageResultFactory;
import com.holly.unit.db.api.pojo.druid.DruidProperties;
import com.holly.unit.db.api.pojo.page.PageResult;
import com.holly.unit.db.api.util.DatabaseUtil;
import com.holly.unit.deform.api.pojo.online.pojo.ColumnInfo;
import com.holly.unit.deform.api.pojo.online.pojo.DesignFormDataPojo;
import com.holly.unit.deform.api.pojo.rsp.DeformResult;
import com.holly.unit.deform.entity.DesignForm;
import com.holly.unit.deform.entity.DesignFormData;
import com.holly.unit.deform.mapper.DeformDataMapper;
import com.holly.unit.deform.util.DatabaseDeFormUtil;
import com.holly.unit.deform.util.DeformUtil;
import com.holly.unit.deform.util.EsQueryWrapperUtil;
import com.holly.unit.dict.modular.entity.SysDict;
import com.holly.unit.dict.modular.service.DictService;
import com.holly.unit.query.api.enums.MatchTypeEnum;
import com.holly.unit.system.api.OrganizationServiceApi;
import com.holly.unit.system.api.pojo.organization.HrOrganizationDTO;
import com.qiniu.util.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.util.HtmlUtils;

import javax.annotation.Resource;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 类描述: 表单设计数据服务类
 *
 * @author fxr
 * @version 1.0.0
 * @date 2022/4/6 9:52
 */
@Service
@Slf4j
public class DeformDataService extends ServiceImpl<DeformDataMapper, DesignFormData> {

    @Autowired
    private DeformDataMapper designFormDataMapper;

    @Autowired
    private DeformBaseInfoService deformBaseInfoService;

    @Autowired
    private DeformAuthService deformAuthService;

    @Resource
    private DruidProperties druidProperties;


    @Resource
    private OrganizationServiceApi organizationServiceApi;

    @Resource
    private DictService dictService;

    /***
     * 批量保存导入的数据
     * @param designForm
     * @param entityList
     * @param token
     * @return
     */
    public boolean saveBatchByImport(DesignForm designForm, Collection<JSONObject> entityList, String token) {
        List<DesignFormData> formData = new ArrayList<>();
        // 请求 header
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.parseMediaType(MediaType.APPLICATION_JSON_UTF8_VALUE));
        headers.set("Accept", MediaType.APPLICATION_JSON_UTF8_VALUE);
        headers.set("X-Access-Token", token);
        // 遍历导入的数据，插入到数据表和online物理表中
        for (JSONObject entity : entityList) {
            DesignFormData data = new DesignFormData();
            data.setDesformId(designForm.getId());
            data.setDesformCode(designForm.getDesformCode());
            data.setDesformName(designForm.getDesformName());
            data.setOnlineFormCode(designForm.getCgformCode());
            data.setDesformDataJson(entity.toJSONString());
            // 如果绑定了 online 表单，就同步导入到物理表
            // TODO 待优化
            if (StrUtil.isNotBlank(designForm.getCgformCode())) {
                String url = RestUtil.getBaseUrl() + "/online/cgform/api/crazyForm/" + designForm.getCgformCode();
                JSONObject res = RestUtil.request(url, HttpMethod.POST, headers, null, entity, JSONObject.class).getBody();
                if (res != null) {
                    String dataId = res.getString("result");
                    data.setOnlineFormDataId(dataId);
                }
            }
            formData.add(data);
        }
        boolean result = super.saveBatch(formData);
        // 保存成功，同步至 ElasticSearch 索引
        if (result) {
            for (DesignFormData designFormData : formData) {
                DeformUtil.asyncSaveOrUpdateEsIndex(designForm.getDesformCode(), designFormData);
            }
        }
        return result;
    }

    /***
     * 根据高级查询条件查询分页数据
     * @param desformCode
     * @param pageNo
     * @param pageSize
     * @param queryWrapper
     * @param superQueryList
     * @param matchType
     * @return
     */
    public DeformResult<PageResult<DesignFormData>> pageList(String desformCode, int pageNo, int pageSize, QueryWrapper<DesignFormData> queryWrapper, JSONArray superQueryList, MatchTypeEnum matchType){

        DeformResult<PageResult<DesignFormData>> result = new DeformResult();
        result.setMessage("查询成功");

        Boolean fillFlag = EsQueryWrapperUtil.fillQueryWrapper(desformCode, queryWrapper, superQueryList, matchType);
        if (fillFlag != null && !fillFlag) {
            result.setMessage("查询成功，但高级查询失败");
        }
        Page<DesignFormData> page = this.page(PageFactory.defaultPage(), queryWrapper);
        PageResult<DesignFormData> pageData = PageResultFactory.createPageResult(page);
        result.setResult(pageData);
        return result;
    }

    /***
     * 根据高级查询条件查询分页数据
     * @param desformCode
     * @param pageNo
     * @param pageSize
     * @param queryWrapper
     * @param superQuery
     * @param username
     * @return
     * @throws UnsupportedEncodingException
     */
    public DeformResult<PageResult<DesignFormData>> queryPage(String desformCode, int pageNo, int pageSize, QueryWrapper<DesignFormData> queryWrapper, String superQuery, String username) throws UnsupportedEncodingException{
        DeformResult<PageResult<DesignFormData>> result = new DeformResult();
        DeformResult get = this.queryPageOrList(desformCode, queryWrapper, superQuery, pageNo, pageSize, false, username);
        BeanUtil.copyProperties(get, result);
        return result;
    }


    /***
     * 根据高级查询条件查询列表数据
     * @param desformCode
     * @param queryWrapper
     * @param superQuery
     * @param username
     * @return
     * @throws UnsupportedEncodingException
     */
    public DeformResult<List<DesignFormData>> queryList(String desformCode, QueryWrapper<DesignFormData> queryWrapper, String superQuery, String username) throws UnsupportedEncodingException {
        DeformResult<List<DesignFormData>> result = new DeformResult<>();
        DeformResult get = this.queryPageOrList(desformCode, queryWrapper, superQuery, 0, 0, true, username);
        BeanUtil.copyProperties(get, result);
        return result;
    }

    /***
     * 通过主表ID查询数据
     * @param mainId
     * @return
     */
    public List<DesignFormData> selectByMainId(String mainId) {
        return designFormDataMapper.selectByMainId(mainId);
    }


    public DeformResult addOne(DesignFormData designFormData) {
        DeformResult<String> result = new DeformResult<>();
        if (designFormData == null) {
            result.error500("designFormData 不能为空！");
            return result;
        }
        try {

            String desformCode = designFormData.getDesformCode();
            if (StrUtil.isEmpty(desformCode)) {
                return DeformResult.error("必须传递 desformCode 参数");
            }

            // 根据code查询出desform的数据
            DesignForm designForm = deformBaseInfoService.getByCode(desformCode);
            if (designForm == null) {
                return DeformResult.error("不存在的 desformCode");
            }

            // 判断是否是子表
            if (CommonConstant.DESIGN_FORM_TYPE_SUB.equals(designForm.getDesformType())) {
                designFormData.setDesformId(designForm.getParentId());
                designFormData.setDesformCode(designForm.getParentCode());
            } else {
                designFormData.setDesformId(designForm.getId());
            }
            designFormData.setDesformName(designForm.getDesformName());

            super.save(designFormData);

            // 异步保存或更新 ElasticSearch 索引数据
            DeformUtil.asyncSaveOrUpdateEsIndex(designForm.getDesformCode(), designFormData);

            // 返回新增的id
            result.setResult(designFormData.getId());
            result.success("添加成功！");
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            result.error500("操作失败");
        }
        return result;
    }


    public DeformResult editOne(DesignFormData designFormData) {
        DeformResult<String> result = new DeformResult<>();
        DesignFormData designFormEntity = super.getById(designFormData.getId());
        if (designFormEntity == null) {
            result.error500("未找到对应数据!");
        } else {
            designFormData.setDesformId(null);
            designFormData.setDesformCode(null);
            super.updateById(designFormData);

            // 异步保存或更新 ElasticSearch 索引数据
            DeformUtil.asyncSaveOrUpdateEsIndex(designFormEntity.getDesformCode(), designFormData);

            result.setResult(designFormData.getId());
            result.success("修改成功!");
        }
        return result;
    }


    public DeformResult deleteOne(DesignFormData designFormData, String token) {
        designFormData = super.getById(designFormData.getId());
        if (designFormData == null) {
            return DeformResult.error("未找到对应实体");
        } else {
            super.removeById(designFormData.getId());
            syncRemoveOnlineData(designFormData, token);
            // 异步删除 ElasticSearch 索引数据
            DeformUtil.asyncDeleteEsIndex(designFormData.getDesformCode(), designFormData);
            return DeformResult.ok("删除成功");
        }
    }

    public DeformResult deleteOne(String id, String token) {
        DesignFormData designFormData = new DesignFormData();
        designFormData.setId(id);
        return this.deleteOne(designFormData, token);
    }


    @Transactional(rollbackFor = Exception.class)
    public void deleteBatchMain(List<String> idList, String token) {
        List<DesignFormData> list = baseMapper.selectList(new LambdaQueryWrapper<DesignFormData>().in(DesignFormData::getId, idList));
        for (DesignFormData designFormData : list) {
            designFormDataMapper.deleteById(designFormData.getId());
            syncRemoveOnlineData(designFormData, token);
            // 异步删除 ElasticSearch 索引数据
            DeformUtil.asyncDeleteEsIndex(designFormData.getDesformCode(), designFormData);
        }
    }
    /**
     * 查询一张表的一条记录
     * 该查询是查询所有字段即select * from {table} where id = {onlineDataId}
     * @param tbname 表名
     * @param onlineDataId 数据id
     * @return
     */
    public Map<String,Object> queryOneByTableNameAndId(String tbname,String onlineDataId) {
        return designFormDataMapper.queryOneByTableNameAndId(tbname,onlineDataId);
    }

    /**
     * 通过表名获取子表配置
     * @param tableName
     * @return
     */
    public String getSubTablesByTableName(String tableName){
        return designFormDataMapper.getSubTablesByTableName(tableName);
    }

    /***
     * 根据主键id查询 实体信息
     * @param dataId
     * @return
     */
    public DesignFormData selectById(String dataId) {
        return designFormDataMapper.selectById(dataId);
    }



    /**
     * 如果关联了online表单，就同步删除
     */
    private void syncRemoveOnlineData(DesignFormData designFormData, String token) {
        String onlineFormCode = designFormData.getOnlineFormCode();
        String onlineDataId = designFormData.getOnlineFormDataId();
        if (StrUtil.isNotBlank(onlineFormCode) && StrUtil.isNotBlank(onlineDataId)) {
            // 请求 header
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.parseMediaType(MediaType.APPLICATION_JSON_UTF8_VALUE));
            headers.set("Accept", MediaType.APPLICATION_JSON_UTF8_VALUE);
            headers.set("X-Access-Token", token);
            // 请求地址
            String url = RestUtil.getBaseUrl() + String.format("/online/cgform/api/formByCode/%s/%s", onlineFormCode, onlineDataId);
            RestUtil.request(url, HttpMethod.DELETE, headers, null, null, JSONObject.class);
        }
    }

    /****************************************************工具类********************************************************/
    private DeformResult queryPageOrList(String desformCode, QueryWrapper<DesignFormData> queryWrapper, String superQuery, int pageNo, int pageSize, boolean queryList, String username) throws UnsupportedEncodingException {
        JSONObject superQueryJSON = JSON.parseObject(superQuery);
        MatchTypeEnum matchType = MatchTypeEnum.getByValue(superQueryJSON.getString("matchType"));
        JSONArray superQueryList = this.getSuperQueryList(superQueryJSON);
        superQueryList = deformAuthService.queryDataAuth(desformCode,username,queryWrapper,superQueryList);
        DeformResult<Object> result = new DeformResult<>();
        result.setMessage("查询成功");
        Boolean fillFlag = EsQueryWrapperUtil.fillQueryWrapper(desformCode, queryWrapper, superQueryList, matchType);
        if (fillFlag != null && !fillFlag) {
            result.setMessage("查询成功，但高级查询失败");
        }

        if (queryList) {
            result.setResult(super.list(queryWrapper));
        } else {
            Page<DesignFormData> page = this.page(PageFactory.defaultPage(), queryWrapper);
            PageResult<DesignFormData> pageData = PageResultFactory.createPageResult(page);
            result.setResult(pageData);
        }
        return result;
    }

    /**
     * 从 superQueryJSON 里取出高级查询列表
     *
     * @param superQueryJSON
     * @return
     * @throws UnsupportedEncodingException
     */
    private JSONArray getSuperQueryList(JSONObject superQueryJSON) throws UnsupportedEncodingException {
        String superQueryParams = superQueryJSON.getString("superQueryParams");
        JSONArray superQueryList = new JSONArray();
        if (StrUtil.isNotBlank(superQueryParams)) {
            superQueryParams = URLDecoder.decode(superQueryParams, "UTF-8");
            superQueryList = JSON.parseArray(superQueryParams);
        }
        return superQueryList;
    }

    public DeformResult editFormData(DesignFormDataPojo designFormData) {
        String tableName =designFormData.getTableName();
        Map<String,Object> filedValues = designFormData.getFormDataMap();
        Map<String, Object> busiData = designFormDataMapper.getFormData(designFormData.getTableId(), tableName);
        //查询表字段信息
        List<ColumnInfo> originalTableColumn = DatabaseDeFormUtil.findOriginalTableColumn(druidProperties, tableName);
        Map<String, ColumnInfo> table = originalTableColumn.stream().collect(Collectors.toMap(ColumnInfo::getFieldName, Function.identity()));
        if (MapUtil.isNotEmpty(busiData)){ //没有，新增逻辑
            StringBuilder setSql = new StringBuilder();
            for (String filed : designFormData.getFiledNames().split(",")) {
                //判断数据库表字段是否包含页面提交的字段
                if(table.containsKey(filed)) {
                    String parameter = filedValues.get(filed) + "";
                    if (StrUtil.isEmpty(parameter)) {
                        setSql.append(String.format("`%s` = null,", filed));
                    } else {
                        setSql.append(String.format("`%s` = '%s',", filed, parameter));
                    }
                }
            }
            String substring = setSql.substring(0, setSql.length()-1);//去掉最后一个,号
            designFormDataMapper.updateFormData(String.format("update %s set %s where id = '%s'","`"+tableName+"`",substring,designFormData.getTableId()));
        }else {
            return DeformResult.error("未找到对应数据");
        }
        return DeformResult.ok("修改成功");
    }

    public DeformResult addFormData(DesignFormDataPojo designFormData) {
        DeformResult<String> result = new DeformResult<>();
        try {
            String tableName =designFormData.getTableName();
            Map<String,Object> filedValues = designFormData.getFormDataMap();
            String tableId = IdUtil.simpleUUID();
            StringBuilder filedsB = new StringBuilder("id");
            StringBuilder filedsVB = new StringBuilder("'"+tableId+"'");
            //查询表字段信息
            List<ColumnInfo> originalTableColumn = DatabaseDeFormUtil.findOriginalTableColumn(druidProperties, tableName);
            Map<String, ColumnInfo> table = originalTableColumn.stream().collect(Collectors.toMap(ColumnInfo::getFieldName, Function.identity()));
            for (String filed : designFormData.getFiledNames().split(",")) {
                //判断数据库表字段是否包含页面提交的字段
                if(table.containsKey(filed)){
                    String v = filedValues.get(filed)+"";
                    if(StrUtil.isNotEmpty(v)){
                        filedsB.append(",`"+filed+"`");
                        filedsVB.append(",'"+filedValues.get(filed)+"'");
                    }
                }
            }
            designFormDataMapper.insertFormData(String.format("INSERT INTO %s (%s) VALUES (%s)","`"+tableName+"`",filedsB.toString(),filedsVB.toString()));
            // 返回新增的id
            result.setResult(designFormData.getTableId());
            result.success("添加成功！");
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            result.error500("操作失败");
        }
        return result;
    }

    public DeformResult queryFormDataList(DesignFormDataPojo designFormData) {
        DeformResult<List> result = new DeformResult<>();
        try {
            StringBuffer sb = new StringBuffer();
            String query = HtmlUtils.htmlUnescape(designFormData.getSuperQuery());
            JSONObject superQueryJSON = JSONObject.parseObject(query);
            String superQueryParams =  superQueryJSON.getString("superQueryParams");
            if(StrUtil.isNotEmpty(superQueryParams)){
                String matchType = superQueryJSON.getString("matchType");
                JSONArray superQueryList = new JSONArray();
                superQueryList = JSON.parseArray(superQueryParams);
                for (int i = 0; i < superQueryList.size(); i++) {
                    JSONObject temp = superQueryList.getJSONObject(i);
                    String field = temp.getString("field");
                    String val = temp.getString("val");
                    QueryRuleEnum rule = QueryRuleEnum.getByValue(temp.getString("rule"));
                    if (rule != null) {
                        switch (rule) {
                            case IN: // 在...中
                                String[] valArr = val.split(",");
                                if (valArr.length > 0) {
                                    StringBuffer stringBuffer = new StringBuffer();
                                    for (int j = 1; j < valArr.length; j++) {
                                        stringBuffer.append("'"+valArr[j]+"'");
                                    }
                                    sb.append(matchType + " " + field + " " + rule.getValue() + "("+stringBuffer.toString()+") ");
                                }
                                break;
                            case LIKE: // 包含
                                sb.append(matchType + " " + field + " " +"like '%"+ val + "%' ");
                                break;
                            case LEFT_LIKE: // 以..结尾
                                sb.append(matchType + " " + field + " " +"like '%"+ val + "' ");
                                break;
                            case RIGHT_LIKE: // 以..开始
                                sb.append(matchType + " " + field + " " +"like '"+ val +"%' ");
                                break;
                            default:
                                sb.append(matchType + " " + field + " " + rule.getValue() + " '" +val + "' ");
                                break;
                        }
                    }
                }
            }
            List<Map<String, Object>> formData = designFormDataMapper.queryFormDataList(PageFactory.defaultPage(),designFormData.getTableName(),sb.toString());
            //获取表单数据结构数据将对应的组件数据查询出来
            DesignForm designForm=deformBaseInfoService.getByCgformCode(designFormData.getTableName());
            String tableJson=designForm.getDesformDesignJson();
            JSONObject object=JSONObject.parseObject(tableJson);
            JSONArray modeArray= JSONArray.parseArray(object.getString("list"));
           /* for(int i=0;i<modeArray.size();i++) {
                String model = modeArray.getJSONObject(i).getString("model");
                String type = modeArray.getJSONObject(i).getString("type");
                //转换部门组件
                if (type.equals("select-depart")) {
                    //转换用户组件数据
                    formData = this.convertDepart(model, formData);
                }
                //转换数据字典
                if(type.equals("select-dict")){
                    JSONObject options=modeArray.getJSONObject(i).getJSONObject("options");
                   if(options.getString("dictCode")!=null) {
                       String dictCode = options.getString("dictCode");
                       formData = this.convertDepart(dictCode, model, formData);
                   }
                }
                //图片js转换
                if(type.equals("imgupload")){
                    formData=this.convertImgData(model,formData);
                }
                //关联数据
                if(type.equals("select-data")){
                    formData=this.converSelectData(model,formData);
                }
                //转换附件信息
                if(type.equals("file-upload")){
                    formData=this.convertFileData(model,formData);
                }
            }*/
            jsonValue(modeArray,formData);

            result.setResult(formData);
            result.success("查询成功！");
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            result.error500("查询失败");
        }
        return result;
    }

    private void jsonValue(JSONArray dataList,List<Map<String, Object>> listData) {
        for(int i=0;i<dataList.size();i++) {
            JSONObject json = dataList.getJSONObject(i);
            String type = json.getString("type");
            if(type.equals("grid")){
                json.getJSONArray("columns").forEach(gridList -> {
                    JSONArray list = ((JSONObject)gridList).getJSONArray("list");
                    if (list.size() > 0) {
                        this.jsonValue(list,listData);
                    }
                });
            }else if(type.equals("card")){
                JSONArray list = json.getJSONArray("list");
                if (list.size() > 0) {
                    this.jsonValue(list,listData);
                }
            }else if(type.equals("sub-table-design")){
                json.getJSONArray("columns").forEach(subList -> {
                    JSONArray listSub = ((JSONObject) subList).getJSONArray("list");
                    if (listSub.size() > 0) {
                        this.jsonValue(listSub,listData);
                    }
                });
            }else {
                String model = json.getString("model");
                //转换部门组件
                if (type.equals("select-depart")) {
                    //转换用户组件数据
                    this.convertDepart(model, listData);
                }
                //转换数据字典
                if(type.equals("select-dict")){
                    JSONObject options=dataList.getJSONObject(i).getJSONObject("options");
                    if(options.getString("dictCode")!=null) {
                        String dictCode = options.getString("dictCode");
                        this.convertDepart(dictCode, model, listData);
                    }
                }
                //图片js转换
                if(type.equals("imgupload")){
                    this.convertImgData(model,listData);
                }
                //关联数据
                if(type.equals("select-data")){
                    this.converSelectData(model,listData);
                }
                //转换附件信息
                if(type.equals("file-upload")){
                    this.convertFileData(model,listData);
                }
            }
        }
    }


    //转换部门数据
    public  List<Map<String, Object>> convertDepart(String model,List<Map<String, Object>> maps){
          List<Long> ids =new ArrayList<>();
          for(int i=0;i<maps.size();i++ ){
              if(maps.get(i).get(model)!=null) {
                List<String> idList= Arrays.asList(maps.get(i).get(model).toString().split(","));
                for(String id :idList){
                    ids.add(Long.parseLong(id));
                }
              }
          }
          if(ids!=null && ids.size()>0) {
              //查询部门信息替换maps
              List<HrOrganizationDTO> list = organizationServiceApi.orgListByIds(ids);
              for (int i = 0; i < maps.size(); i++) {
                  if(maps.get(i).get(model)!=null) {
                      List<String> nameList=new ArrayList<>();
                      List<String> idList= Arrays.asList(maps.get(i).get(model).toString().split(","));
                      for(String id:idList){
                          HrOrganizationDTO dto = list.stream().filter(n -> n.getOrgId().equals(Long.parseLong(id))).findFirst().orElse(null);
                          if (dto != null) {
                              nameList.add(dto.getOrgName()) ;
                          }
                      }
                      maps.get(i).put(model, StringUtils.join(nameList,","));
                  }
              }
          }
         //返回maps;
         return maps;
    }

    //转换字典数据
    public List<Map<String,Object>> convertDepart(String dictCode, String model,List<Map<String, Object>> maps){
          //根据code获取字典信息
         List<SysDict> list= dictService.list(new QueryWrapper<SysDict>().eq("dict_type_code",dictCode));
         if(list!=null && list.size()>0) {
             for (int i = 0; i < maps.size(); i++) {
                 if( maps.get(i).get(model)!=null) {
                     String code = maps.get(i).get(model).toString();
                     SysDict dict = list.stream().filter(n -> n.getDictCode().equals(code)).findFirst().orElse(null);
                     if (dict != null) {
                         maps.get(i).put(model, dict.getDictName());
                     }
                 }
             }
         }
        return maps;
    }

    //转换图片数据
    public List<Map<String,Object>> convertImgData(String model,List<Map<String, Object>> maps ){
        for (int i = 0; i < maps.size(); i++) {
            if(maps.get(i).get(model)!=null) {
                String imgData = maps.get(i).get(model).toString();
                 maps.get(i).put(model, HtmlUtils.htmlUnescape(imgData));
            }
        }
        return maps;
    }

    //转换附件
    public List<Map<String,Object>> convertFileData(String model,List<Map<String, Object>> maps ){
        for (int i = 0; i < maps.size(); i++) {
            if(maps.get(i).get(model)!=null) {
                String imgData = maps.get(i).get(model).toString();
                maps.get(i).put(model, HtmlUtils.htmlUnescape(imgData));
            }
        }
        return maps;
    }

    /**
     * 转换关联数据
     * @param model
     * @param maps
     * @return
     */
    public List<Map<String,Object>> converSelectData(String model,List<Map<String, Object>> maps ){
        for (int i = 0; i < maps.size(); i++) {
            if(maps.get(i).get(model)!=null) {
                if(ObjectUtil.isNotNull(maps.get(i).get(model))){
                    String data = maps.get(i).get(model).toString();
                    if (ObjectUtil.isNotNull(data) && !"".equals(data)) {
                        String json = HtmlUtils.htmlUnescape(data);
                        Collection values = JSONObject.parseObject(json).values();
                        maps.get(i).put(model,StringUtils.join(values, ","));
                    }
                }
            }
        }
        return maps;
    }



    public DeformResult delFormData(DesignFormDataPojo designFormData) {
        DeformResult<String> result = new DeformResult<>();
        try {
            designFormDataMapper.deleteFormData(designFormData.getTableId(),designFormData.getTableName());
            result.success("删除成功！");
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            result.error500("操作失败");
        }
        return result;
    }

    public void deleteBatchForm(List<String> asList, String tableName) {
        designFormDataMapper.deleteBatchForm(asList,tableName);
    }

    public void addTableData(List<Map<String, Object>> projectSiteList,String tableName) {
        //查询表字段信息
        List<ColumnInfo> originalTableColumn = DatabaseDeFormUtil.findOriginalTableColumn(druidProperties, tableName);
        Map<String, ColumnInfo> maps = originalTableColumn.stream().collect(Collectors.toMap(ColumnInfo::getColComment, p -> p, (k, v) -> k));
        List<String> list = new ArrayList<>();
        for (Map<String,Object> dataValue : projectSiteList){
            String tableId = IdUtil.simpleUUID();
            StringBuilder filedsB = new StringBuilder("id");
            StringBuilder filedsVB = new StringBuilder("'"+tableId+"'");
            for(Map.Entry<String, Object> entry : dataValue.entrySet()){
                if(maps.containsKey(entry.getKey())){
                    ColumnInfo columnInfo = maps.get(entry.getKey());
                    filedsB.append(",`"+columnInfo.getFieldName()+"`");
                    filedsVB.append(",'"+entry.getValue()+"'");
                }
            }
            if(filedsB.length() > 1){
                list.add(String.format("INSERT INTO %s (%s) VALUES (%s)","`"+tableName+"`",filedsB.toString(),filedsVB.toString()));
            }
        }
        if(list.size() > 0 ){
            DatabaseUtil.executeDDL(druidProperties, list);
        }
    }
}
